import axiosIns from '../../utils/axios';
import update, { updateChain } from 'immutability-helper-x';
import { couponList } from '../../utils/mock';
/**
|--------------------------------------------------
|  Constants
|--------------------------------------------------
*/
const COU_LOADING = 'COU_LOADING';
const GETLIST = 'GETLIST';
const GETDATASOURCE = 'GETDATASOURCE';
/**
|--------------------------------------------------
| Actions
|--------------------------------------------------
*/
export function getList(params) {
  return async (dispatch, getState) => {
    const { loading } = getState().coupon;
    if (loading) return;
    dispatch({ type: COU_LOADING });
    const res = await axiosIns('/getCouponList');
    const { data } = res;
    dispatch({ type: GETDATASOURCE, datasource: data.list });
    dispatch(filter(params));
  };
}
export function filter(params) {
  return async (dispatch, getState) => {
    const { datasource } = getState().coupon;
    const { state } = params;
    let list = [].concat(datasource);
    if (state != 'all') {
      list = list.filter(item => item.state == state);
    }
    dispatch({ type: GETLIST, list });
  };
}
/**
|--------------------------------------------------
| Action Handlers
|--------------------------------------------------
*/
const ACTION_HANDLERS = {
  [GETDATASOURCE]: (state, action) => {
    return { ...state, loading: false, datasource: action.datasource };
  },
  [GETLIST]: (state, action) => {
    return { ...state, loading: false, list: action.list };
  },
  [COU_LOADING]: state => {
    console.log('coupon loading');
    return { ...state, loading: true };
  }
};
/**
|--------------------------------------------------
| Reducer
|--------------------------------------------------
*/
const initialState = {
  list: null,
  datasource: null,
  loading: false
};
export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];
  return handler ? handler(state, action) : state;
}
